<?php
namespace app\api\controller;

use think\Controller;

/**
 * 公用基础控制器
 */
class BaseController extends Controller {

	protected function _initialize() {
		parent::_initialize();
		header('Access-Control-Allow-Origin:*');
		//验证key,是否非法访问
	}

	/**
	 * 返回成功带提示信息
	 * @param msg 操作成功或操作失败
	 * @param error=false
	 */
	protected function toSuccess($msg = '操作成功', $data = '') {
		$json['msg'] = $msg;
		if ($data) {
			$json['data'] = $data;
		}
		$json['error'] = false;
		return json($json);
	}

	/**
	 * 返回成功不带提示信息
	 * @param data
	 * @param error=false
	 */
	protected function toData($data) {
		$json['data'] = $data;
		$json['error'] = false;
		return json($json);
	}

	/**
	 * 返回失败带提示信息
	 * @param msg
	 * @param data 可以为空
	 * @param error=true
	 */
	protected function toError($msg = '没有查到数据', $data = '') {
		$json['msg'] = $msg;
		if ($data) {
			$json['data'] = $data;
		}
		$json['error'] = true;
		return json($json);
	}

	/**
	 * 单图片上传
	 * $oss 是否上传到OSS
	 */
	protected function upload($cate = 'temp') {
		$file = request()->file('file');
		$info = $file->move(ROOT_PATH . 'uploads');
		if ($info) {
			$src = '/' . str_replace('\\', '/', $info->getSaveName());
			if (config('aliyun_oss')) {
				// 上传到OSS
				$res = $this->oss_img($cate . '/' . date('Ymd') . '/' . $info->getFilename(), './uploads' . $src);
				if ($res) {
					$result = array(
						'code' => 1,
						'msg' => '上传成功',
						'src' => 'https://' . config('aliyun.bucket') . '.' . config('aliyun.endpoint') . '/' . $cate . $src
					);
				} else {
					$result = array(
						'code' => 0,
						'msg' => $res
					);
				}
			} else {
				if ($info) {
					$result = array(
						'code' => 1,
						'src' => '/uploads' . $src
					);
				} else {
					$result = array(
						'code' => 0,
						'msg' => $file->getError()
					);
				}
			}
		} else {
			$result = array(
				'code' => 0,
				'msg' => $file->getError()
			);
		}
		return $result;
	}

	private function oss_img($object, $path) {
		//去阿里云后台获取秘钥
		$config = config('aliyun');
		//实例化OSS
		try {
			$ossClient = new \OSS\OssClient($config['app_key'], $config['app_secret'], $config['endpoint']);
			//uploadFile的上传方法
			$ossClient->uploadFile($config['bucket'], $object, $path);
		} catch(\OSS\Core\OssException $e) {
			//如果出错这里返回报错信息
			return $e->getMessage();
		}
		//否则，完成上传操作
		return true;
	}

}
